<template>
  <div class="w-full flex flex-col justify-center  items-center px-5 py-6">

    <Motion class="tabs bg-white bg-clip-text shadow-xl">
      <Motion
          :initial="{
            borderBottomWidth:'1px',
          }"
          @click="[tabsIndex=0,animate_tabs($event)]" :class="[{'tab-active':tabsIndex==0},'tab']">
        综合
      </Motion>
      <Motion
          :initial="{
            borderBottomWidth:'1px',
          }"
          @click="[tabsIndex=1,animate_tabs($event)]" :class="[{'tab-active':tabsIndex==1},'tab']">
        歌曲
      </Motion>
      <Motion
          :initial="{
            borderBottomWidth:'1px',
          }"
          @click="[tabsIndex=2,animate_tabs($event)]" :class="[{'tab-active':tabsIndex==2},'tab']">
        歌单
      </Motion>
      <Motion
          :initial="{
            borderBottomWidth:'1px',
          }"
          @click="[tabsIndex=3,animate_tabs($event)]" :class="[{'tab-active':tabsIndex==3},'tab']">
        用户
      </Motion>
    </Motion>

    <!--用户-->
    <Motion
        :initial="{
          opacity:0,
        }"
        :in-view="{
          opacity:1,
        }"
        :transition="{
          duration:1,
          easing: 'ease-in-out'
        }"
        v-if="tabsIndex==0 ||tabsIndex==3" class="w-full mt-6 flex justify-center items-center">
      <div
          class="max-w-screen-xl w-full text-base bg-base-100 border border-black/20 shadow-2xl flex flex-col justify-center items-center rounded-2xl px-5">
        <div class="h-1/6 w-full flex flex-row justify-center items-end border-white/30 border-b py-3">
          <div class="w-full flex justify-start items-center  text-xl pl-2">用户</div>
        </div>
        <div v-if="userPageConfig?.content.length != 0"
             class="h-5/6 w-full flex flex-1 flex-col justify-center items-center">
          <div v-for="(user,index) in userPageConfig?.content" :key="index"
               :class="[{'mb-6': userPageConfig?.content.length -1 == index},'hover:rounded-2xl hover:bg-gradient-to-r hover:from-primary/20 hover:via-secondary/10 hover:to-primary/0 select-none w-full h-16 flex flex-row justify-center items-center']">
            <div class="w-full flex flex-row justify-start items-center">
              <img v-if="user?.['avatar'] != null" class="avatar  w-12 h-12 object-cover  rounded-full   mx-2"
                   :src="user?.['avatar']">
              <div v-else class="btn btn-primary flex justify-center items-center text-2xl  w-12 h-12 mx-2 rounded-full">
                {{ user?.['username'].substring(0,1).toUpperCase() }}
              </div>
              <div class="w-full">
                <div class="w-full flex justify-start items-center text-md">
                  {{ user?.['username'] }}
                </div>
                <div class="w-full overflow-clip flex justify-start items-center text-xs">{{
                    user?.['remark']
                  }}
                </div>
              </div>
            </div>
          </div>
          <div v-if="(userPageConfig.totalElements - (userPageConfig.pageIndex ) * 6) > 0 "
               @click="[update_SongList()]"
               class="select-none w-full h-12 flex flex-col justify-center items-center">
            查看全部{{ userPageConfig.totalElements - (userPageConfig.pageIndex ) * 6 }}个用户
          </div>
        </div>
        <div v-else class="h-16 flex justify-center items-center ">暂无</div>
      </div>
    </Motion>
    <!--搜索歌曲-->
    <Motion
        :initial="{
          opacity:0,
        }"
        :in-view="{
          opacity:1,
        }"
        :transition="{
          duration:1,
          easing: 'ease-in-out'
        }"
        v-if="tabsIndex==0 ||tabsIndex==1" class="w-full mt-6 flex justify-center items-center">
      <div
          class="max-w-screen-xl w-full text-base bg-base-100 border border-black/20 shadow-2xl flex flex-col justify-center items-center rounded-2xl px-5">
        <div class="h-1/6 w-full flex flex-row justify-center items-end border-white/20 border-b py-3">
          <div class="w-6/12 flex justify-start items-center text-xl pl-2">单曲</div>
          <div class="w-6/12 flex justify-end items-center ">
            <button v-if="songPageConfig?.content.length > 0 " @click="hook_addSongsToPlayerList(songPageConfig?.['content'],true,true)" class="btn btn-xs rounded-3xl border">播放全部</button>
          </div>
        </div>
        <div v-if="songPageConfig?.content.length != 0"
             class="h-5/6 w-full flex flex-1 flex-col justify-center items-center">
          <div v-for="(song,index) in songPageConfig.content" :key="index"
               :class="[{'mb-6': songPageConfig?.content.length -1 == index},'hover:rounded-2xl hover:bg-gradient-to-r hover:from-secondary/20 hover:via-primary/10 hover:to-primary/0 select-none w-full h-16 flex flex-row justify-center items-center pl-2']">
            <div @click="toSongInfoPage(song?.['id'])"
                class="w-10/12  flex flex-col justify-start items-center">
              <div class="w-full flex justify-start items-center text-md">{{ song?.['name'] }}</div>
              <div class="w-full overflow-clip flex justify-start items-center text-xs">{{
                  song?.['singer']
                }}
              </div>
            </div>
            <label :for="'song' + index"  class="w-2/12  flex justify-center items-center">
              <svg class=" btn btn-sm btn-circle border-opacity-0 bg-opacity-0 " xmlns="http://www.w3.org/2000/svg"
                   fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor">
                <path stroke-linecap="round" stroke-linejoin="round"
                      d="M12 6.75a.75.75 0 110-1.5.75.75 0 010 1.5zM12 12.75a.75.75 0 110-1.5.75.75 0 010 1.5zM12 18.75a.75.75 0 110-1.5.75.75 0 010 1.5z"/>
              </svg>
            </label>
            <!-- Put this part before </body> tag -->
            <input type="checkbox" :id="'song' + index" class="modal-toggle" />
            <div class="modal">
              <div class="modal-box flex flex-col">
                <h3 class="font-bold text-lg">歌曲: {{ song?.['name'] + "-" + song?.['singer'] }}</h3>
                <label @click="addSongToFavorite(song?.['id'])" :for="'song' + index" class="btn btn-primary my-2">添加到我喜欢</label>
                <label @click="updatePlaylist()" :for="'modal_add'+ song?.id" class="btn btn-secondary my-2">添加到歌单</label>
                <div class="modal-action">
                  <label :for="'song' + index" class="btn btn-error">关闭</label>
                </div>
              </div>
            </div>

            <input type="checkbox" :id="'modal_add'+ song?.id" class="modal-toggle"/>
            <div class="modal">
              <label class="modal-box">
                <label :for="'modal_add'+ song?.id" class="btn btn-sm btn-circle absolute right-2 top-2">✕</label>
                <h3 class="text-lg font-bold">{{ song['name'] }}</h3>
                <p class="py-4">将歌曲添加至下列歌单中</p>
                <label v-for="(playlist,index) in playlists"
                       :for="'modal_add'+ song?.id"
                       @click="addSongToPlaylist(playlist?.['id'], song?.['id'])"
                       :class="['btn btn-primary w-full max-w-sm my-2']"
                       :key="index">
                  {{ playlist?.['name'] + '-' + playlist?.['remark'] }}
                </label>
              </label>
            </div>

          </div>
          <div v-if="(songPageConfig.totalElements - (songPageConfig.pageIndex ) * 6) > 0 "
               @click="[update_SongList()]"
               class="select-none w-full h-12 flex flex-col justify-center items-center">
            查看全部{{ songPageConfig.totalElements - (songPageConfig.pageIndex ) * 6 }}首歌曲
          </div>
        </div>
        <div v-else class="h-16 flex justify-center items-center ">暂无</div>
      </div>
    </Motion>
    <!--搜索歌单-->
    <Motion
        :initial="{
          opacity:0,
        }"
        :in-view="{
          opacity:1,
        }"
        :transition="{
          duration:1,
          easing: 'ease-in-out'
        }"
        v-if="tabsIndex==0 ||tabsIndex==2" class="w-full mt-6 flex justify-center items-center">
      <div
          class="max-w-screen-xl w-full text-base bg-base-100 border border-black/20 shadow-2xl flex flex-col justify-center items-center rounded-2xl px-5">
        <div class="h-1/6 w-full flex flex-row justify-center items-end border-white/20 border-b py-3">
          <div class="w-full flex justify-start items-center text-xl pl-2">歌单</div>
        </div>
        <div v-if="playlistPageConfig?.content.length != 0"
             class="h-5/6 w-full flex flex-1 flex-col justify-center items-center" @click.stop>
          <div v-for="(playlist,index) in playlistPageConfig?.content"
               :key="index"
               :class="[{'mb-6': playlistPageConfig?.content.length -1 == index},'hover:rounded-2xl hover:bg-gradient-to-r hover:from-primary/20 hover:via-secondary/10 hover:to-primary/0 select-none w-full h-16 flex flex-row justify-center items-center pl-2']">
            <div @click="toPlaylistPage(playlist?.['id'])" class="w-10/12  flex flex-col justify-start items-center">
              <div class="w-full flex justify-start items-center text-md">{{ playlist?.['name'] }}</div>
              <div class="w-full overflow-clip flex justify-start items-center text-xs">
                {{ playlist?.['remark'] }}
              </div>
            </div>
            <label v-if="useAuthStore().isAuthenticated?? false" @click="addPlaylistToFavorite(playlist?.['id'])">
              <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="w-6 h-6">
                <path stroke-linecap="round" stroke-linejoin="round" d="M12 9v6m3-3H9m12 0a9 9 0 11-18 0 9 9 0 0118 0z" />
              </svg>
            </label>

          </div>
          <div v-if="(playlistPageConfig.totalElements - (playlistPageConfig.pageIndex) * 6) > 0 "
               @click="[update_SongList()]"
               class="select-none w-full h-12 flex flex-col justify-center items-center">
            查看全部{{ playlistPageConfig.totalElements - (playlistPageConfig.pageIndex) * 6 }}个歌单
          </div>
        </div>
        <div v-else class="h-16 flex justify-center items-center ">暂无</div>
      </div>
    </Motion>
  </div>
</template>

<script setup lang="ts">
import {onBeforeMount, reactive, ref, watch} from "vue";
import {hook_getSongPageByKeyword} from "../hook/SongHook.ts";
import {Motion} from "@motionone/vue";
import {animate} from "motion";
import {
  hook_addPlaylist,
  hook_addPlaylistSong,
  hook_findPlaylistByKeyword,
  hook_findPlaylistsByUserId,
  hook_getPlaylistPageByKeyword
} from "../hook/PlaylistHook.ts";
import {hook_findUserByKeyword, hook_getFavorite, hook_getUser, hook_getUserPageByKeyword} from "../hook/UserHook.ts";
import {
  hook_addPlaylistToFavorite,
  hook_addSongToFavorite, hook_checkPlaylistIsFavorite,
  hook_checkSongIsFavorite, hook_deleteFavoritePlaylistByUserId,
  hook_deleteFavoriteSongByUserId
} from "../hook/FavoriteHook.ts";
import router from "../plugins/router.ts";
import {hook_addSongsToPlayerList, hook_addSongToPlayerList} from "../hook/SongPlayerHook.ts";
import {useAuthStore} from "../plugins/pinia.ts";


//TODO data

let props = defineProps<{
  keyword
}>()

let tabsIndex = ref(0);

//TODO 生命周期
onBeforeMount(async () => {
  await update_SongList();
  await update_PlaylistList();
  await update_UserList();
})


//TODO watch
watch(() => props.keyword, async () => {
  Object.assign(songPageConfig,{
    pageIndex: 0,
    totalElements: 0,
    totalPages: 0,
    content: []
  })
  Object.assign(playlistPageConfig,{
    pageIndex: 0,
    totalElements: 0,
    totalPages: 0,
    content: []
  })
  Object.assign(userPageConfig,{
    pageIndex: 0,
    totalElements: 0,
    totalPages: 0,
    content: []
  })
  await update_SongList();
  await update_PlaylistList();
  await update_UserList();
})

//TODO function

//songPage
let songPageConfig = reactive({
  pageIndex: 0,
  totalElements: 0,
  totalPages: 0,
  content: []
});

async function update_SongList() {
  let data = await hook_getSongPageByKeyword(props.keyword, songPageConfig.pageIndex);
  console.log(data?.['content'])

  songPageConfig.totalElements = data?.['totalElements']
  songPageConfig.totalPages = data?.['totalPages']

  if (data?.['content'].length > 0) {
    songPageConfig.content = _.concat(songPageConfig.content,data?.['content']);
  }
  songPageConfig.pageIndex++
}


//playlistPage
let playlistPageConfig = reactive({
  pageIndex: 0,
  totalElements: 0,
  totalPages: 0,
  content: []
});

async function update_PlaylistList() {
  let data = await hook_getPlaylistPageByKeyword(props.keyword,playlistPageConfig.pageIndex);

  playlistPageConfig.totalElements = data?.['totalElements']
  playlistPageConfig.totalPages = data?.['totalPages']

  if (data?.['content'].length > 0) {
    playlistPageConfig.content = _.concat(playlistPageConfig.content,data?.['content']);
  }
  playlistPageConfig.pageIndex++
}

//userPage
let userPageConfig = reactive({
  pageIndex: 0,
  totalElements: 0,
  totalPages: 0,
  content: []
});
async function update_UserList() {
  let data = await hook_getUserPageByKeyword(props.keyword,userPageConfig.pageIndex);

  userPageConfig.totalElements = data?.['totalElements']
  userPageConfig.totalPages = data?.['totalPages']

  if (data?.['content'].length > 0) {
    userPageConfig.content = _.concat(userPageConfig.content,data?.['content']);
  }
  userPageConfig.pageIndex++
}


//TODO 动画
function animate_tabs(event) {
  animate(event.currentTarget, {
    borderBottomWidth: "5px",
  }, {
    duration: 0.1,
    easing: "linear",
  })
  animate($(event.currentTarget).siblings().get(), {
    borderBottomWidth: "1px",
  }, {
    duration: 0.1,
    easing: "linear",
  })
}


//TODO 添加到我喜欢
async function addSongToFavorite(songId) {
  let isFavorite = await hook_checkSongIsFavorite(hook_getFavorite()['id'], songId)
  if (isFavorite) {
    await hook_deleteFavoriteSongByUserId(hook_getUser().id,songId)
  } else {
    await hook_addSongToFavorite(songId)
  }
}

function addSongToPlaylist(playlistId, songId) {
  hook_addPlaylistSong(playlistId, songId)
}

let playlists = ref()
async function updatePlaylist() {
  playlists.value = await hook_findPlaylistsByUserId(hook_getUser().id)
}

function toPlaylistPage(playlistId) {
  router.push("/playlist/" + playlistId)
}

function toSongInfoPage(songId) {
  router.push("/songInfo/" + songId)
}

//歌单添加到收藏
let isFavorite = ref(false)
async function addPlaylistToFavorite(id) {
  await hook_addPlaylistToFavorite(id);
}

</script>

<style scoped>

</style>